﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;

namespace Futurism.Universal.Foundation
{
    public class RegionManager 
    {
        private Dictionary<string, Region> regions = new Dictionary<string, Region>();

        private Dictionary<Type, object> regionAdapters = new Dictionary<Type,object>();

        //private Dictionary<string, View> views = new Dictionary<string, View>();

        private TypeContainer container;

        public RegionManager(TypeContainer container)
        {
            this.container = container;
            RegisterRegionAdapter<Grid>(new GridRegionAdapter());
            RegisterRegionAdapter<ContentPage>(new ContentPageRegionAdapter());
        }

        public void RegisterRegion(string regionKey, VisualElement region, RegionAdapter regionAdapter = null)
        {
            if (regionAdapter == null)
            {
                regionAdapter = regionAdapters[region.GetType()] as RegionAdapter;
            }

            regions[regionKey] = new Region { RegionAdapter = regionAdapter, Wrapper = region };
        }

        public void RegisterRegionAdapter<T>(RegionAdapter adapter)
            where T : VisualElement
        {
            regionAdapters.Add(typeof(T), adapter);
        }

        public void Navigate(string regionKey, string newViewName, object navigationContext = null)
        {
            var region = regions[regionKey];
            var regionAdapter = region.RegionAdapter;
            var oldView = regionAdapter.GetContent(region.Wrapper);

            var oldViewModel = oldView != null ? oldView.BindingContext as NavigationViewModel : null;

            if (oldViewModel != null)
            {
                if (oldViewModel.CanNavigatingFrom())
                {
                    oldViewModel.CanNavigatingFrom();
                }
            }

            var newView = container.Resolve(newViewName) as View;

            var newViewModel = newView.BindingContext as NavigationViewModel;

            if (newViewModel != null)
            {
                newViewModel.OnNavigatedTo(navigationContext);
            }

            regionAdapter.SetContant(region.Wrapper, newView);
        }
    }
}
